package com.example.lib_base.utils

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Typeface
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.style.ForegroundColorSpan
import android.text.style.RelativeSizeSpan
import android.text.style.StyleSpan
import androidx.annotation.ColorInt

/**
 * 把密度转换为像素
 */
fun dip2px(context: Context, px: Float): Int {
    val scale = getScreenDensity(context)
    return (px * scale + 0.5).toInt()
}

/**
 * 得到设备的密度
 */
private fun getScreenDensity(context: Context): Float {
    return context.resources.displayMetrics.density
}

/**
 * 单独对textView中某字体设置样式
 *
 * 默认加粗
 */

@SuppressLint("ResourceType")
fun setTextStyle(
    context: Context,
    text: String,
    textSize: Float = 1f,
    @ColorInt textColor: Int = 0x000000,
    array: Array<String>?
): SpannableStringBuilder {
    val builder = SpannableStringBuilder(text)
    if (array == null || array.size % 2 != 0) {
        return builder
    }
    for (index in 0..array.size / 2) {
        if (index * 2 + 1 <= array.size) {
            val colorSpan = ForegroundColorSpan(context.resources.getColor(textColor))
            val fontWeightSpan = StyleSpan(Typeface.BOLD)
            val fontSize = RelativeSizeSpan(textSize)
            builder.setSpan(
                colorSpan,
                builder.indexOf(array[index * 2]) + 1,
                builder.indexOf(array[index * 2 + 1]),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
            )
            builder.setSpan(
                fontWeightSpan,
                builder.indexOf(array[index * 2]) + 1,
                builder.indexOf(array[index * 2 + 1]),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
            )
            builder.setSpan(
                fontSize,
                builder.indexOf(array[index * 2]) + 1,
                builder.indexOf(array[index * 2 + 1]),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
            )
        }
    }
    return builder
}
